package hash;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description: 15.三数之和
 * User: Li_yizYa
 * Date: 2025—04—02
 * Time: 22:06
 */
public class Solution7 {
    public static void main(String[] args) {
        int[] nums = {-1,0,1,2,-1,-4};
        List<List<Integer>> ret = threeSum(nums);
        for (List<Integer> tmp : ret) {
            for (int num : tmp) {
                System.out.print(num + " ");
            }
            System.out.println();
        }
    }

    private static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ret = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return ret;
        }
        // 首先对 nums 进行排序
        Arrays.sort(nums);

        for (int i = 0; i < nums.length; i++) {
            // 如果排序后第一个数大于 0 ，则无结果
            if (nums[i] > 0) {
                return ret;
            }

            // 去重
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }

            int left = i + 1;
            int right = nums.length - 1;
            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                if (sum > 0) {
                    right--;
                } else if (sum < 0) {
                    left++;
                } else {
                    ret.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    while (left < right && nums[right] == nums[right - 1]) {
                        right--;
                    }
                    while (left < right && nums[left] == nums[left + 1]) {
                        left++;
                    }
                    left++;
                    right--;
                }
            }
        }
        return ret;
    }
}
